package com.company.beauty.common.retry;

import cn.hutool.extra.spring.SpringUtil;
import com.company.beauty.common.utils.Executors;
import com.company.beauty.common.utils.ServiceNotifyUtil;
import com.company.nuwa.common.key.ApplicationNamedKeyGenerator;
import com.company.nuwa.redis.support.lock.RedisLocker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;

import java.util.List;
import java.util.concurrent.*;

/**
 * <p>retry job bootstrap startup runner</p >
 *
 * @author youyoukele
 * @version 1.0
 * @date 2024/1/31 19:20
 */
@Slf4j
public class RetryJobBootstrapStartupRunner implements CommandLineRunner {

    private final RetryRequestHandler retryRequestHandler = RetryRequestHandlerFactory.getRetryRequestHandler();
    private final RedisLocker redisLocker = SpringUtil.getBean(RedisLocker.class);
    private final ScheduledThreadPoolExecutor scheduled = Executors.newScheduledThreadPool(1, "schedule-retry");

    @Override
    public void run(final String... args) {
        log.info("retry job bootstrap startup runner start");
        scheduled.scheduleWithFixedDelay(this::execute, 0, 60, TimeUnit.SECONDS);
    }

    /**
     * execute
     */
    private void execute() {
        log.info("retry job bootstrap startup runner execute");
        String lockKey = genRetryRequestHandleKey();
        redisLocker.tryLock(lockKey, 60, TimeUnit.SECONDS, () -> {
            List<RetryRequest> retryList = retryRequestHandler.getRetryList();
            log.info("execute retry list:{}", retryList);
            for (RetryRequest request : retryList) {
                ServiceNotifyUtil.Result result = ServiceNotifyUtil.callback(request.getUrl(), request.getRequestBody(), Boolean.FALSE);
                log.info("callback request:{}, result:{}", request, result);
                if (result.isResult()) {
                    // 执行成功后，从队列移除
                    retryRequestHandler.removeRetry(request);
                }
            }
            return Boolean.TRUE;
        });
    }

    /**
     * 注意，该队列为服务级别隔离
     * key的格式:  xxxx-service:RETRY_QUEST_HANDLE
     *
     * @return
     */
    private String genRetryRequestHandleKey() {
        return ApplicationNamedKeyGenerator.genKey("RETRY_REQUEST_HANDLE");
    }
}
